import moment from 'moment';

import { systemUtil } from './native';

interface Event {
  key: string;
  detail: { [key: string]: any };
}

/**
 * 只对detail的第一层value做转换string处理，如果properties的value > 128字符，则会展示不出来
 * 建议：detail里面只写一层object，不要object嵌套
 * TODO: 如果有多层嵌套，则都解析出来，转换成只有一级的object
 * 官方解释：
 * Once you have started the SDK, use the trackEvent method to track your events with properties.
 * You can send up to 200 distinct event names. Also, there is a maximum limit of 256 characters
 * per event name and 125 characters per event property name and event property value.
 */
const event = ({ key, detail }: Event): void => {
  let localDetail = detail;
  Object.keys(detail).forEach((item): void => {
    localDetail[item] =
      typeof detail[item] === 'object'
        ? JSON.stringify(detail[item])
        : `${detail[item]}`;
  });
  localDetail = {
    ...detail,
    deviceId: systemUtil.getAppDeviceId(),
    appName: systemUtil.getPackageId(),
    appVersion: systemUtil.getAppVersion(),
    deviceProduct: systemUtil.getDeviceProduct(),
    channel: systemUtil.getVersionChannel(),
    time: moment().format('YYYY-MM-DD HH:mm:ss')
  };
};

export default event;

export const EVENT_REQUEST_ERROR = 'request error';
